<template>
  <div class="roll-call-container">
    <!-- 页面标题与装饰 -->
    <div class="page-header">
      <div class="title-decoration left"></div>
      <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-white text-center drop-shadow-md">随机点名系统</h1>
      <div class="title-decoration right"></div>
      <p class="text-blue-100 text-center mt-2 opacity-90">点击开始按钮，抽取幸运学生</p>
    </div>

    <!-- 核心点名容器（带动态背景） -->
    <div class="roll-call-core">
      <!-- 背景动态光斑 -->
      <div class="bg-light spot1"></div>
      <div class="bg-light spot2"></div>
      <div class="bg-light spot3"></div>

      <!-- 结果展示卡片（悬浮玻璃质感） -->
      <div class="result-card glass-effect">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <div class="loader"></div>
          <p class="text-white mt-4 opacity-80">加载学生名单中...</p>
        </div>

        <!-- 未点名状态 -->
        <div v-else-if="!isRolling && !selectedStudent" class="empty-state">
          <i class="fa fa-user-o text-6xl text-white opacity-70"></i>
          <p class="text-white mt-4 opacity-90">点击下方按钮开始点名</p>
        </div>

        <!-- 滚动中状态 -->
        <div v-if="isRolling" class="rolling-state">
          <div class="rolling-box">
            <div class="rolling-text">正在随机抽取...</div>
          </div>
          <div class="progress-dot">
            <span :class="{ active: dotActive }"></span>
          </div>
        </div>

        <!-- 点名结果状态 -->
        <div v-else-if="!isRolling && selectedStudent" class="result-state">
          <!-- 头像（带入场动画） -->
          <div class="student-avatar" :style="avatarStyle">
            <span class="avatar-text">{{ selectedStudent.username.substring(0, 1) }}</span>
          </div>

          <!-- 学生信息 -->
          <div class="student-info">
            <h2 class="student-name">{{ selectedStudent.username }}</h2>
            <div class="student-details">
              <span class="id-tag">ID: {{ selectedStudent.id }}</span>
              <span class="gender-tag" :class="selectedStudent.sex === 1 ? 'male' : 'female'">
                {{ selectedStudent.sex === 1 ? '男生' : selectedStudent.sex === 0 ? '女生' : '未知' }}
              </span>
            </div>
          </div>

          <!-- 结果标识 -->
          <div class="result-badge">
            <i class="fa fa-trophy"></i>
            <span>幸运学生</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="control-btn-group">
      <button
          @click="toggleRoll"
          :disabled="loading || (students.length === 0)"
          class="main-btn"
          :class="{ rolling: isRolling, disabled: loading || (students.length === 0) }"
      >
        <i class="fa" :class="isRolling ? 'fa-stop' : 'fa-play'"></i>
        <span>{{ isRolling ? '停止抽取' : '开始点名' }}</span>
      </button>

      <button
          @click="refreshStudents"
          :disabled="loading || isRolling"
          class="refresh-btn"
          :class="{ disabled: loading || isRolling }"
      >
        <i class="fa fa-refresh"></i>
        <span>刷新名单</span>
      </button>
    </div>

    <!-- 点名历史（折叠式） -->
    <div class="history-panel">
      <div class="panel-header" @click="toggleHistory">
        <h3 class="panel-title">
          <i class="fa fa-history"></i>
          点名历史
          <span class="history-count">({{ historyList.length }})</span>
        </h3>
        <i class="fa" :class="historyOpen ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
      </div>

      <div class="panel-content" v-show="historyOpen">
        <div v-if="historyList.length === 0" class="empty-history">
          <p>暂无点名记录</p>
        </div>
        <ul class="history-list">
          <li v-for="(item, index) in historyList" :key="index" class="history-item">
            <span class="history-name">{{ item.username }}</span>
            <span class="history-time">{{ item.time }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { getStudents } from "../../Api/User";

export default {
  name: "RollCall",
  data() {
    return {
      // 学生数据（页面加载后立即获取）
      students: [],
      loading: false,

      // 点名状态
      isRolling: false,
      selectedStudent: null,
      rollingTimer: null,
      dotActive: false,
      historyOpen: false,
      randomResult: null,

      // 动画相关
      avatarStyle: {
        transform: "scale(0)",
        opacity: "0"
      },

      // 点名历史
      historyList: []
    };
  },
  created() {
    // 页面初始化时立即获取学生名单
    this.refreshStudents();
  },
  mounted() {
    // 启动背景光斑动画
    this.startSpotAnimation();
  },
  methods: {
    // 刷新学生数据（页面加载后自动调用，确保先获取所有学生再点名）
    async refreshStudents() {
      this.loading = true;
      try {
        const res = await getStudents();
        if (res && res.code === "200" && Array.isArray(res.data)) {
          this.students = res.data;
          this.selectedStudent = null;
          this.showToast("success", "学生名单已更新", `共加载 ${this.students.length} 名学生`);
        } else {
          this.students = [];
          this.showToast("error", "加载失败", res?.msg || "无法获取学生数据");
        }
      } catch (error) {
        console.error("获取学生数据失败：", error);
        this.students = [];
        this.showToast("error", "请求错误", "获取学生数据时发生异常");
      } finally {
        this.loading = false;
      }
    },

    // 开始/停止点名（确保只有在获取到学生后才能开始）
    toggleRoll() {
      if (this.students.length === 0) {
        this.showToast("warning", "无数据", "请先刷新加载学生名单");
        return;
      }

      this.isRolling ? this.stopRolling() : this.startRolling();
    },

    // 开始点名（已获取所有学生后才能触发）
    startRolling() {
      this.isRolling = true;
      this.selectedStudent = null;
      this.dotActive = false;

      // 滚动动画定时器
      this.rollingTimer = setInterval(() => {
        this.dotActive = !this.dotActive;
      }, 500);

      // 从已加载的学生名单中随机抽取
      this.randomResult = this.students[Math.floor(Math.random() * this.students.length)];
    },

    // 停止点名（展示结果）
    stopRolling() {
      this.isRolling = false;
      clearInterval(this.rollingTimer);

      // 结果入场动画
      this.selectedStudent = this.randomResult;
      this.avatarStyle = {
        transform: "scale(1)",
        opacity: "1",
        transition: "all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)",
        background: `linear-gradient(45deg, #${Math.floor(Math.random()*16777215).toString(16)}, #${Math.floor(Math.random()*16777215).toString(16)})`
      };

      // 添加到历史记录
      this.addToHistory(this.selectedStudent);
    },

    // 添加历史记录
    addToHistory(student) {
      const now = new Date();
      const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;

      this.historyList.unshift({
        id: student.id,
        username: student.username,
        time: timeStr
      });

      // 限制历史记录数量
      if (this.historyList.length > 10) {
        this.historyList.pop();
      }
    },

    // 切换历史面板显示/隐藏
    toggleHistory() {
      this.historyOpen = !this.historyOpen;
    },

    // 动态光斑动画
    startSpotAnimation() {
      const spot1 = document.querySelector('.spot1');
      const spot2 = document.querySelector('.spot2');
      const spot3 = document.querySelector('.spot3');

      if (!spot1 || !spot2 || !spot3) {
        console.warn("光斑元素未找到，跳过光斑动画");
        return;
      }

      const spots = [
        { el: spot1, x: 20, y: 30, size: 150 },
        { el: spot2, x: 80, y: 40, size: 200 },
        { el: spot3, x: 50, y: 70, size: 180 }
      ];

      spots.forEach(spot => {
        spot.el.style.left = `${spot.x}%`;
        spot.el.style.top = `${spot.y}%`;
        spot.el.style.width = `${spot.size}px`;
        spot.el.style.height = `${spot.size}px`;

        setInterval(() => {
          const newX = Math.random() * 100;
          const newY = Math.random() * 100;
          const newSize = 150 + Math.random() * 100;

          spot.el.style.left = `${newX}%`;
          spot.el.style.top = `${newY}%`;
          spot.el.style.width = `${newSize}px`;
          spot.el.style.height = `${newSize}px`;
        }, 5000 + Math.random() * 3000);
      });
    },

    // 提示弹窗
    showToast(type, title, message) {
      const toast = document.createElement('div');
      toast.className = `toast ${type}`;
      toast.innerHTML = `
        <i class="fa ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-exclamation-triangle'}"></i>
        <div class="toast-content">
          <h4>${title}</h4>
          <p>${message}</p>
        </div>
      `;

      document.body.appendChild(toast);
      setTimeout(() => toast.classList.add('show'), 10);
      setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
      }, 3000);
    }
  },
  beforeDestroy() {
    // 清除定时器，避免内存泄漏
    if (this.rollingTimer) clearInterval(this.rollingTimer);
  }
};
</script>

<style scoped>
/* 基础容器样式 */
.roll-call-container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

/* 标题样式 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40px;
  position: relative;
}

.title-decoration {
  width: 50px;
  height: 2px;
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
}

.title-decoration.left {
  left: calc(50% - 120px);
}

.title-decoration.right {
  right: calc(50% - 120px);
}

/* 核心点名区域 */
.roll-call-core {
  max-width: 600px;
  margin: 0 auto;
  position: relative;
}

/* 动态背景光斑 */
.bg-light {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  filter: blur(80px);
  transition: all 8s ease-in-out;
  z-index: 1;
}

/* 玻璃质感卡片 */
.glass-effect {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 60px 20px;
  text-align: center;
  position: relative;
  z-index: 2;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loader {
  width: 48px;
  height: 48px;
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-bottom-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

/* 滚动中状态 */
.rolling-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.rolling-box {
  width: 280px;
  height: 80px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rolling-text {
  color: white;
  font-size: 1.2rem;
}

.progress-dot {
  margin-top: 20px;
}

.progress-dot span {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transition: all 0.3s;
}

.progress-dot span.active {
  background: white;
  box-shadow: 0 0 10px white;
}

/* 点名结果状态 */
.result-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

/* 头像样式 */
.student-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  box-shadow: 0 0 20px rgba(255, 255, 255, 0.5);
}

.avatar-text {
  color: white;
  font-size: 3rem;
  font-weight: bold;
}

/* 学生信息 */
.student-info {
  text-align: center;
  margin-bottom: 20px;
}

.student-name {
  font-size: 2rem;
  color: white;
  font-weight: bold;
  margin-bottom: 10px;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}

.student-details {
  display: flex;
  gap: 20px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
}

/* 结果标识 */
.result-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
  color: white;
  font-weight: bold;
  box-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
}

.result-badge i {
  color: gold;
}

/* 控制按钮 */
.control-btn-group {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.main-btn, .refresh-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 30px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.main-btn:hover, .refresh-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-3px);
}

.main-btn.rolling {
  background: rgba(255, 50, 50, 0.7);
}

.main-btn.disabled, .refresh-btn.disabled {
  background: rgba(255, 255, 255, 0.1);
  cursor: not-allowed;
  transform: none;
}

/* 历史面板 */
.history-panel {
  max-width: 600px;
  margin: 40px auto 0;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 20px;
  border-radius: 20px 20px 0 0;
  cursor: pointer;
}

.panel-title {
  color: white;
  font-weight: bold;
}

.history-count {
  font-weight: normal;
  opacity: 0.7;
}

.panel-content {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 0 0 20px 20px;
  max-height: 200px;
  overflow-y: auto;
  transition: max-height 0.3s ease;
}

.empty-history {
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
  padding: 20px 0;
}

.history-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.history-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.8);
}

/* 提示弹窗 */
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(-100px);
  padding: 15px 30px;
  border-radius: 30px;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  opacity: 0;
  transition: all 0.3s;
  z-index: 9999;
}

.toast.show {
  transform: translateX(-50%) translateY(0);
  opacity: 1;
}

.toast.success {
  background: rgba(50, 205, 50, 0.8);
}

.toast.error {
  background: rgba(220, 50, 50, 0.8);
}

.toast.warning {
  background: rgba(255, 165, 0, 0.8);
}

.toast-content h4 {
  margin: 0 0 5px 0;
  font-weight: bold;
  color: white;
}

.toast-content p {
  margin: 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.9rem;
}
</style>
